-module(misc_timer).

-behaviour(gen_server).
%%
%% Include files
%%
-include("common.hrl").

%%
%% Exported Functions
%%
-export([now/0, now_seconds/0, now_milseconds/0, cpu_time/0, start_link/0, start/1, info/0]).

-export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]).

%%
%% API Functions
%%
now() ->
	[{timer, {Now, _}}] = ets:lookup(ets_timer, timer),
	Now.

now_seconds() ->
	util:unixtime().

now_milseconds() ->
	util:longunixtime().

cpu_time() ->
	[{time, {_, Wallclock_Time_Since_Last_Call}}] = ets:lookup(ets_timer, timer),
	Wallclock_Time_Since_Last_Call.

info() ->
	[
	 ets:info(ets_timer),
	 ets:tab2list(ets_timer)
	 ].

%%
%% Local Functions
%%
-define(CLOCK, 100).

start(Sup) -> 
	supervisor:start_child(Sup, {misc_timer,
								 {misc_timer, start_link, []},
								permanent, brutal_kill, worker, [misc_timer]}).

start_link() ->
	gen_server:start_link({local, ?MODULE}, ?MODULE, [], []).

init([]) ->
	ets:new(ets_timer, [set, protected, named_table]),
	ets:insert(ets_timer, {timer, {erlang:now(), 0}}),
	erlang:send_after(?CLOCK, self(), {event, clock}),
	misc:write_monitor_pid(self(), ?MODULE, {}),
	{ok, []}.

handle_call(_Request, _From, State) ->
	{reply, State, State}.

handle_cast(_Msg, State) ->
	{noreply, State}.

handle_info({event, clock}, State) ->
	{_Total_Run_Time, Time_Since_Last_Call} = statistics(runtime),
	ets:insert(ets_timer, {timer, {erlang:now(), Time_Since_Last_Call}}),
	erlang:send_after(?CLOCK, self(), {event, clock}),
	{noreply, State};

handle_info(_info, State) ->
	{noreply, State}.

terminate(_Reason, _State) ->
	misc:delete_monitor_pid(self()),
	ok.

code_change(_OldVsn, State, _Extra) ->
	{ok, State}.


